<template>
  <div class="scroll-wrapper" ref="wrapper">
    <div class="scroll-content">
      <div v-if="!errorShow">
        <view-list
          v-if="field === 'view'"
          :viewDatas="listData[cityId]"
        ></view-list>
        <food-list
          v-if="field === 'food'"
          :viewDatas="listData[cityId]"
        ></food-list>
        <hotel-list
          v-if="field === 'hotel'"
          :viewDatas="listData[cityId]"
        ></hotel-list>
        <massage-list
          v-if="field === 'massage'"
          :viewDatas="listData[cityId]"
        ></massage-list>
        <ktv-list
          v-if="field === 'ktv'"
          :viewDatas="listData[cityId]"
        ></ktv-list>
        <loading :loadingShow="loadingShow"></loading>
      </div>
      <error :errorShow="errorShow" />
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import BetterScroll from "better-scroll";
import { ListModel } from "models/list";

import ViewList from "./ViewList";
import Foodist from "./Foodist";
import Hotelist from "./Hotelist";
import Massagelist from "./Massagelist";
import KtvList from "./KtvList";
import Loading from "./Sub/Loading";
import Error from "./Sub/Error";

import tools from "utils/tools";
export default {
  name: "ListScrollWrapper",
  components: {
    ViewList,
    Foodist,
    Hotelist,
    KtvList,
    Massagelist,
    Loading,
    Error,
  },
  data() {
    return {
      errorShow: false,
      loadingShow: false,
      listData: {},
    };
  },
  computed: {
    ...mapState(["cityId", "field"]),
  },
  /**
   * 监听城市切换变化
   */
  watch: {
    cityId() {
      this.getListDatas(this.cityId, this.field);
    },
  },
  mounted() {
    let scroll = new BetterScroll(this.$refs.wrapper);
    this.getListDatas(this.cityId, this.field);
  },
  methods: {
    getListDatas(cityId, field) {
      // 如果不存在缓存数据
      if (!this.listData[cityId]) {
        const listModel = new ListModel();

        this.listData = [];
        this.loadingShow = true;

        listModel.getListDatas(cityId, field).then((res) => {
          if (res && res.status === 0) {
            const data = tools.formatJSON(res.data, "keyword");

            this.errorShow = false;
            setTimeout(() => {
              // 缓存指定 cityId 的数据
              this.listData[cityId] = data;
              this.loadingShow = false;
            }, 500);
          } else {
            this.errorShow = true;
          }
        });
      }
    },
  },
};
</script>
